<template>
  <div class="create-post-container">
    <h1>创建帖子</h1>
    <form class="post-form" @submit.prevent="submitPost">
      <div class="form-group">
        <label for="title">标题</label>
        <input
          type="text"
          id="title"
          v-model="postForm.title"
          placeholder="请输入帖子标题"
          required
        >
      </div>
      <div class="form-group">
        <label for="category">分类</label>
        <select id="category" v-model="postForm.category" required>
          <option value="">请选择分类</option>
          <option v-for="category in categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
      </div>
      <div class="form-group">
        <label for="postType">帖子类型</label>
        <select id="postType" v-model="postForm.postType" required>
          <option value="second_hand">二手市场</option>
          <option value="dating">恋爱交友</option>
          <option value="help">打听求助</option>
          <option value="job">发布兼职</option>
          <option value="gossip">校园八卦</option>
          <option value="other">其他</option>
        </select>
      </div>
      <div class="form-group">
        <div class="checkbox-group">
          <input type="checkbox" id="allowComment" v-model="postForm.allowComment">
          <label for="allowComment">允许评论（默认开启）</label>
        </div>
      </div>
      <div class="form-group">
        <label for="content">内容</label>
        <textarea
          id="content"
          v-model="postForm.content"
          placeholder="请输入帖子内容"
          rows="10"
          required
        ></textarea>
      </div>
      <div class="form-group">
        <label for="tags">标签（可选）</label>
        <input
          type="text"
          id="tags"
          v-model="postForm.tags"
          placeholder="请输入标签，用逗号分隔"
        >
      </div>
      <div class="form-group">
        <label>上传图片（可选）</label>
        <input type="file" multiple @change="handleFileUpload">
        <div class="preview-images" v-if="previewUrls.length > 0">
          <img v-for="(url, index) in previewUrls" :key="index" :src="url" alt="预览图" @click="removeImage(index)">
        </div>
      </div>
      <button type="submit" class="submit-btn">发布帖子</button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { circleApi } from '@/api'

const router = useRouter()
const categories = ref([])
const postForm = ref({
  title: '',
  content: '',
  category: '',
  postType: 'other',
  tags: '',
  images: [],
  allowComment: true
})
const previewUrls = ref([])

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await circleApi.getCategories()
    categories.value = res.data
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 处理文件上传预览
const handleFileUpload = (e) => {
  const files = e.target.files
  if (files.length > 0) {
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      const reader = new FileReader()
      reader.onload = (e) => {
        previewUrls.value.push(e.target.result)
        postForm.value.images.push(file)
      }
      reader.readAsDataURL(file)
    }
  }
}

// 移除预览图片
const removeImage = (index) => {
  previewUrls.value.splice(index, 1)
  postForm.value.images.splice(index, 1)
}

// 提交帖子
const submitPost = async () => {
  try {
    // 处理表单数据
    const formData = new FormData()
    formData.append('title', postForm.value.title)
    formData.append('content', postForm.value.content)
    formData.append('category', postForm.value.category)
    formData.append('post_type', postForm.value.postType)
    formData.append('allow_comment', postForm.value.allowComment)
    
    // 处理标签 - 由于当前前端没有获取标签列表，暂时不传递标签数据
    // 注意：不要将空数组作为字符串'[]'传递，而是应该不传递该字段或者传递实际的空数组
    
    // 添加图片文件 - 直接添加文件，后端会处理
    postForm.value.images.forEach((image, index) => {
      formData.append(`images`, image)
    })

    // 提交创建帖子请求
    await circleApi.createPost(formData)

    // 跳转回圈子首页
    router.push({ name: 'circle' })
  } catch (error) {
    console.error('创建帖子失败:', error)
    console.error('错误详情:', error.response?.data)
    // 显示更详细的错误信息
    if (error.response?.data) {
      let errorMessage = '创建帖子失败:\n'
      for (const [field, messages] of Object.entries(error.response.data)) {
        errorMessage += `${field}: ${messages.join(', ')}\n`
      }
      alert(errorMessage)
    }
  }
}

// 页面加载时执行
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.create-post-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.post-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
}

.checkbox-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.checkbox-group input[type="checkbox"] {
  width: auto;
  margin: 0;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 16px;
}

.form-group textarea {
  resize: vertical;
}

.preview-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.preview-images img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  padding: 12px 24px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #3aa876;
}
</style>